package ynu.lcy.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.Where;
import ynu.lcy.elememicroservicecommon.entity.LogicEntity;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static ynu.lcy.elememicroservicecommon.constant.CommonConstant.ORDER_STATE_UNPAID;


/*
 * 订单实体
 * */
@Entity
@Setter
@Getter
@ToString
@NoArgsConstructor
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "fieldHandler"})
@Table(name = "orders")
@Where(clause = "is_deleted = 0")
public class Order extends LogicEntity {
    /*
    * 订单总价
    * */
    private Double totalPrice;
    // 订单状态
    @Column(insertable = false,
            nullable = false,
            columnDefinition="INT default 0")
    private Integer orderState; //订单状态（0：未支付； 1：已支付；2：已经确认；3：已退款）
    /*
    * 所属顾客
    * */
    private  Long customerId;

    /**
     * 所属商家
     * */
    private Long businessId;

    /**
     * 配送地址
     * */
    private Long addressId;

    /*
    * 订单细则
    * */
    @OneToMany(cascade = {CascadeType.MERGE,CascadeType.REMOVE,CascadeType.PERSIST},fetch = FetchType.EAGER)
    @JoinColumn(name = "order_id")
    @JsonIgnoreProperties("order")
    private Set<OrderDetails> orderDetails;

    @JsonIgnore
    public Order create(Long businessId,Long userId,Long addressId, List<OrderDetails> orderDetails) {
        this.setBusinessId(businessId);
        this.setCustomerId(userId);
        this.setAddressId(addressId);
        this.setOrderDetails(new HashSet<>(orderDetails));
        this.setTotalPrice(orderDetails.stream().mapToDouble(OrderDetails::getLineItemPrice).sum());
        this.setOrderState(ORDER_STATE_UNPAID);
        this.setIsDeleted(0);
        this.setCreateTime(new Date());
        return this;
    }
}
